package com.fenghuajueli.lib_data.database.manager;

import android.content.Context;

import com.fenghuajueli.lib_data.database.DaoManager;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 通过泛型封装 实例化传入对应的对象 减少创建manager
 *
 * @param <T> 要查询的对象
 * @param <K> 这个表的主键类型
 */
public class ActionDaoManager<T, K> {
    private DaoManager manager;

    public ActionDaoManager(Context context) {
        manager = DaoManager.getInstance();
        manager.init(context);
    }


    public boolean insertData(T entity) {
        return manager.getDaoSession().insertOrReplace(entity) != -1;
    }

    /**
     * 插入多条记录，需要开辟新的线程
     *
     * @param list
     * @return flag
     **/
    public boolean insertList(final List<T> list) {
        boolean flag = false;
        try {
            manager.getDaoSession().runInTx(() -> {
                for (T entity : list) {
                    manager.getDaoSession().insertOrReplace(entity);
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public boolean updateData(T entity) {
        boolean flag = false;
        try {
            manager.getDaoSession().update(entity);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * @return flag
     */
    public boolean delete(T entity) {
        boolean flag = false;
        try {
            manager.getDaoSession().delete(entity);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public void deleteAll(Class<T> classs) {
        manager.getDaoSession().deleteAll(classs);
    }

    /**
     * 按照主键返回单行记录 * * @param key * @return
     */
    public T getOneData(Class<T> classs, K key) {
        return manager.getDaoSession().load(classs, key);
    }

    /**
     * 查询短语表中所有数据
     */
    public List<T> queryAll(Class<T> classs) {
        return manager.getDaoSession().loadAll(classs);
    }

    public List<T> query(Class<T> classs, String where, String... selectionArg) {
        return manager.getDaoSession().queryRaw(classs, where, selectionArg);
    }

    /**
     * 使用queryBuilder进行查询
     */
    public List<T> query(Class<T> classs, WhereCondition cond) {
        QueryBuilder<T> queryBuilder = manager.getDaoSession().queryBuilder(classs);
        return queryBuilder.where(cond).list();
    }

    /**
     * 使用queryBuilder进行查询
     */
    public List<T> query(Class<T> classs, WhereCondition cond,WhereCondition... more) {
        QueryBuilder<T> queryBuilder = manager.getDaoSession().queryBuilder(classs);
        return queryBuilder.where(cond,more).list();
    }
}
